﻿<?php
// 数据库配置 - 与admin.php保持一致
define('DB_HOST', 'localhost');
define('DB_NAME', 'music_db');
define('DB_USER', '73327382');
define('DB_PASS', '73327382');

// 创建数据库连接
try {
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $pdo = new PDO($dsn, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}

// 处理编辑请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取表单数据
    $id = $_POST['id'] ?? 0;
    $title = $_POST['title'] ?? '';
    $artist = $_POST['artist'] ?? '';
    $album = $_POST['album'] ?? '';
    $mp3_url = $_POST['mp3_url'] ?? '';
    
    // 验证数据
    if ($id > 0 && !empty($title) && !empty($artist) && !empty($album) && !empty($mp3_url)) {
        try {
            // 准备更新语句
            $stmt = $pdo->prepare("UPDATE songs SET title = ?, artist = ?, album = ?, mp3_url = ? WHERE id = ?");
            $stmt->execute([$title, $artist, $album, $mp3_url, $id]);
            
            // 返回成功响应
            header('Content-Type: application/json');
            echo json_encode(['success' => true, 'message' => '歌曲更新成功!']);
            exit;
        } catch (PDOException $e) {
            // 返回错误响应
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => '更新失败: ' . $e->getMessage()]);
            exit;
        }
    } else {
        // 返回验证失败响应
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => '所有字段都必须填写!']);
        exit;
    }
}

// 如果不是POST请求，返回错误
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => '无效的请求方法']);
exit;
?>